package com.winning.util.ncpquery.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;


/**
 *
 */
@Slf4j
public class SSLClientUtil {

	private static SSLContext sslcontext;
	
	static {
		
			log.info("开始初始化 https 对象");
			InputStream keystream = null;
			InputStream truststream = null;
			String keyStorePasswordText = "";
			String trustKeyStorePasswordText = "";
			try {
				keystream = null;
				truststream =null;
				
				keyStorePasswordText = null;
				trustKeyStorePasswordText =null;
			} catch (Exception e) {
				log.error("获取证书失败");
			}
			try {
				
				KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		        KeyStore trustStore  = KeyStore.getInstance("JKS");
		        
		        try {
		        	keyStore.load(keystream, keyStorePasswordText.toCharArray());
		            trustStore.load(truststream, trustKeyStorePasswordText.toCharArray());
		        } finally {
		        	keystream.close();
		        	truststream.close();
		        }
		        //信任自签名证书，加载客户端证书
		        sslcontext = SSLContexts.custom()
		        		.useProtocol("TLS")
		        		.loadKeyMaterial(keyStore, keyStorePasswordText.toCharArray())
		                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
		                .build();
			} catch (Exception e) {
				log.error("获取证书失败");
			}
		}
	
	/**
	 * 获取 SSLContext 对象
	 * 
	 * @return
	 */
	public static SSLContext getSSLContext(){
        return sslcontext;
	}
}
